//app.js注册小程序App()函数
var http = require('service/http.js');
var util = require('utils/util.js');//工具类
App({
  data: { //全局数据
    //-------------------安全域名-----------------
    baseUrl: 'https://wxcd.momjoin.com.cn', // 'https://www.momjoin.com.cn', //  'http://192.168.1.9:8083', // 'https://wx.mamatx.com.cn',//  
    version: '0.9.1',//本地版本号
    versionUpdate: false,//版本更新
    cityName: '成都',//程序内默认city
    cityArray: [],//全部城市
    isShowAD: 'notYet',//是否展示首页的投放广告
    adDetailArr:[],//广告信息
    adInterval:'',//每张广告投放时间间隔
    showPage: false,//是否展示页面
    countAdTime:'',//广告计时时间
    scrollViewHeight: 0,//滚动窗口高度
    //--------商品加载分页参数page-----------------------
    pageNo: 1,
    pageSize: 10, //分页商品条数
    itemList:[],//按条件查询商品列表
    itemTotal:'',//商品列表总分页页数

    //----------------用户登录初始化-------------------
    loginCode: '',//用于登录获取的code,5分钟之内有效
    codeExpiryTime: 300000,//code过期时间
    loginType: 0, //登录入口，从公众号进入
    isAuthorization: 'notYet', //是否授权登陆
    loginMsg: '',//用于登录检查过期SessionTimeOut
    userInfoScope: false,//用户授权状态

    personOrderInfo: '', //订单信息
    pesonalCartInfo: '', //购物车数量
    customerServicePhone: '',//客服电话

    showLogin: 'notYet', //是否展示登录
    isBindPhone: false, //是否已经绑定手机
    codeTime: 60, //验证码有效时间(默认60秒)
    getCode: false, //是否已经获取验证码
    codeNum: '', //获取得验证码
    showLoadding:true,//加载动画gif

    //--------------------默认商品图片-----------------
    defaultImgUrl: 'https://mamatx.com.cn/order/carouselImgs/default_img.jpg',
    isshow: false,
    opMask: 0,
    toBuy: false,
    skuid: '', //skuid(加入购物和结算使用)
    pid: '', //商品id(加入购物车和结算使用)
    //----加入购物车动画---------------------
    
    animationData: '', //所有动画
    skuTitles: '',
    maskHeight: '', //mask高度
    minPrice: 0, //最小价格（初始化商品价格范围）
    maxPrice: 0, //最大价格
    skus: [], //所有sku内容
    distAttrs: [], //不重复的可选属性值
    chooseAttrids: [], //已选属性id

    isLimited: false, //是否为限购商品
    limitedNum: 0, //限购数量

    //----------暂存购物车商品信息-------------------
    itemId: '', //暂存购物车商品id 
    skuId: '', //skuid
    count: 1, //购物车数量
    stock: 0, //默认库存
    cartStock:0,//用户显示购物车剩余库存
    cartProducts: [], //购物车列表
    //--------分享商品动画------------------------------
   
    shareImgUrl: '', //分享图片地址
    showCanvas: false, //用于生成图片
    windowWidth: 0, //可视窗口大小
    windowHeight: 0,
    codeUrl: '', //分享码地址
 
    //-----------判断是否下单----------------------------
    ispay: false, //是否点击支付
    //-----------按条件搜索返回商品列表----------
    searchList: [],
    inputFocus: false, //是否聚焦
    //-----------购物车商品数量----------------------
    cartCount: 0,
    addcart: false, //是否通过验证可以加入购物车(购物车sku验证)

    //----------商品分享分享人inviter-店铺id------------------------------
    inviter: '', //分享人inviter(通过二维码扫描进入小程序获取)
    shopuid: '', //店铺id
    shopName: '', //店铺名称
    hasShop: false, //自己是否已经拥有分销店铺
    isOwnShop: '', //是否为自己的店铺：1---自己的店铺；0--别人的店铺；null---平台

    //------------   分享妈妈中心页面展示数据---------------------
    personalInviteInfo: {}, //用户分享相关信息（订单＼用户）
    zjuserfxfee: 0, //累计收益

    //分销店铺分享商品，支付后回到分销店铺标识
    userName: '',//用户真实姓名用于用户提现
    hasRealName : false,//用户是否绑定真实姓名

    //------------优惠券-----------------------------------------
    discountCardList:[],//优惠券列表
    //------------------打开设置-------------------------------------
    showSettingBox: false,//打开引导用户设置弹出层
    //-------------------formIdPool池 用于消息推送--------------------
    formIdPool: [],//用于模板消息推送
    
  },
  globalData: {
    userInfo: null,
    products: [], //所有商品列表
    product: {}, //当前正在浏览的商品
  },
  onLaunch: function (option) { //监听小程序初始化，全局只运行一次
    console.log("onLaunch进入appjs监听小程序初始化，全局只运行一次")
    console.log(option);
    //清除本地缓存信息
    this.removeLocalStorage();
    //隐藏底部菜单
    wx.hideTabBar();

    //获取广告轮播
    this.getAdvers();

    //获取城市列表
    this.loadCityArray();
    
    //滚动窗口高度
    this.getViewHeight();

  },

  onShow: function () {//checksession (从后台进入小程序前台) 更改全局data变量
    console.log('app-Onshow');

    let that = this;

    //监听小程序版本更新--清除本地店铺信息
    that.checkVersion();

    //清除formIdPool
    that.data.formIdPool = [];
  },


 //获取广告轮播
  getAdvers:function(){

    let that = this;

    http.getReq('/weixin/zjCarouseImg/advers',{},function(res){
      console.log('引用commonJs请求接口');
      console.log('广告advers');
      console.log(res);

      let [adDetailArr, adInterval, countAdTime, isShowAD, showAdTime] = [that.data.adDetailArr, that.data.adDetailArr, that.data.countAdTime, that.data.isShowAD, that.data.showAdTime];
      adDetailArr = res.zjAdvertImgArr;//广告信息
      if (adDetailArr.length > 0) {
        adInterval = res.interval;//时间间隔
        countAdTime = parseInt(adInterval) * adDetailArr.length;//总时长
        isShowAD = true;
      } else {
        isShowAD = false;
        countAdTime = 0;
      }
      that.data.adDetailArr = adDetailArr;
      that.data.adInterval = adInterval;
      that.data.countAdTime = countAdTime;
      that.data.isShowAD = isShowAD;
      console.log('countAdTime--' + countAdTime);
    });
   
  },

  getViewHeight: function () {  //滚动窗口高度
    var res = wx.getSystemInfoSync();//系统参数
    let [windowWidth, windowHeight] = [res.windowWidth, res.windowHeight];
    let scrollViewHeight = res.windowHeight * 2;
    this.data.scrollViewHeight = scrollViewHeight;//滚动窗口高度
    this.data.windowWidth = windowWidth;//窗口高度
    this.data.windowHeight = windowHeight;//窗口高度
  },
  removeLocalStorage: function () {  //清除本地缓存信息
    console.log('清除店铺信息');
    //初始化本地登录信息
    this.data.isAuthorization = 'notYet';//是否授权登陆
    this.data.isShowAD = 'notYet';//是否授权登陆
    this.data.showLogin = 'notYet';//是否授权登陆
    let shopInfo = wx.getStorageInfoSync('shopInfo');

    if ((shopInfo.isOwnShop || '') !== '1'){
      //清除店铺之前店铺信息
      wx.removeStorageSync('shopInfo');
    }
    //清除地理位置，重新获取
    wx.removeStorageSync('cityName');
  },

  onHide:function(){

   //清空广告数据
    this.removeAdMessage();

   //保存formid
    this.saveFormIdPool();
    
  },

  removeAdMessage: function () {    //清空广告数据

    this.data.adDetailArr = [];
    this.data.adInterval = '';//时长间隔
    this.data.countAdTime = '';//计时时间
    this.data.isShowAD = false;//是否展示广告

  },


  checkVersion: function () { //检查本地版本号更新
    //---------------------检查本地版本号------------------------------
    let [newVersion, version] = [this.data.version, wx.getStorageSync('version')];
    console.log('版本号是否一致：' + (newVersion == version));
    if (newVersion !== version) {
      //更新本地数据
      wx.setStorageSync("version", newVersion);
      this.data.versionUpdate = true;
    }
    console.log('最新版本号：' + newVersion + '；本地版本号：' + version + '；更新后版本号：' + wx.getStorageSync('version'));
  },

  //---------------------检查session 是否过期---------
  checkSession: function (pageData) {
    
    let that = this;
    that.data.isAuthorization = 'notYet';//初始化登录信息
    //获取本地session、本地店铺信息、分享标识
    let rdSession = wx.getStorageSync('rd_session');
    console.log("appjs:checksession：rdSession==" + rdSession);

    //初始化分享店铺信息//本地店铺信息
    let [shopuid, shopInfo] = ['', wx.getStorageSync('shopInfo') || {}];

    //有分享数据--更新shopuid
    shopuid = pageData ? pageData.data.shopuid : shopuid ;

    //请求获取isAuthorization授权状态存储店铺信息
    http.getReq('/weixin/checkSession', { 'rdSession': rdSession }, function (res) {
      
      console.log('checksession 返回信息：');
      console.log(res);
      that.data.loginMsg = res.msg;
      if (res.ret) {//已授权
        if (res.data.isOwnShop == '1' || (!shopuid && res.data.isOwnShop === '0')) {//没有分销店铺信息
          //本地存储店铺信息:店铺id、店铺名称、是否有分销店铺
          shopInfo.shopuid = res.data.shopuid;
          shopInfo.shopName = res.data.shopName;
          shopInfo.isOwnShop = res.data.isOwnShop;
        }
        //更新本地缓存店铺信息
        wx.setStorageSync('shopInfo', shopInfo);

        console.log('已授权不用登陆isAuthorization：true');
        that.data.isAuthorization = true;

        that.getElementsCounts();//获取用户订单、购物车数量
        that.getDiscountCard();//获取优惠券数量
      } else {//未授权 
        that.data.isAuthorization = false;
        return;
      }

      console.log('checkSession后shopInfo：');
      console.log(wx.getStorageSync('shopInfo'));

    });
  },

  //用户登录
  userLogin: function (e,pageData) { 

    let that = this;
    let shopInfo = {};//本地店铺信息

    //初始化分享店铺信息
    let shopuid = '';

    //有分享数据--更新shopuid
    shopuid = pageData ? pageData.data.shopuid : shopuid;

    console.log('第一次关注shopuid：' + shopuid);

    //空字符串拦截
    shopuid = (shopuid == "''" ? '' : shopuid);
    
    //用户信息，用于解密
    let code = that.data.loginCode;
    let [userInfo, iv, encryptedData] = [e.detail.userInfo, e.detail.iv, e.detail.encryptedData];

    //登录--返回：店铺信息shopInfo、手机绑定hasPhoneNum、rd_session、unionid、过期时间expiration
    http.getReq('/weixin/wxUser/login', {
      code: code,
      userInfo: userInfo, //用户信息
      encryptedData: encryptedData, //用户敏感信息
      iv: iv, //加密算法的初始向量,
      shopuid: shopuid, //绑定首次关注使用
    }, function (loginData) {
      //不管登录成功与否）关闭登录动画和登录界面
      console.log("loginData登录返回信息:");
      console.log(loginData);

      //登录成功     
      if (loginData.ret) {
        //自己有店、不是分享店铺 且有绑定关系
        if (loginData.data.isOwnShop === '1' || (loginData.data.isOwnShop === '0' && !shopuid)) {
          shopInfo.shopuid = loginData.data.shopuid;
          shopInfo.shopName = loginData.data.shopName;
          shopInfo.isOwnShop = loginData.data.isOwnShop;
        }

        //本地存储店铺信息:店铺id、店铺名称、是否有分销店铺
        //更新本地缓存店铺信息
        wx.setStorageSync('shopInfo', shopInfo);

        console.log('登录后显示店铺信息：');
        console.log(wx.getStorageSync('shopInfo'));

        //缓存用户信息到本地

        wx.setStorageSync('userInfo', userInfo); //用户信息保存到本地
        wx.setStorageSync('unionid', loginData.data.unionid)
        wx.setStorageSync('isBindPhone', loginData.data.hasPhoneNum)
        wx.setStorageSync("rd_session", loginData.data.rd_session);
        wx.setStorageSync("expiration", loginData.data.expiration) //过期时间

        //更新appjs全局变量
        that.globalData.userInfo = userInfo;
        that.data.isAuthorization = true;
        that.data.showLogin = false;//隐藏登录界面
        that.data.loginCode = '';//清空登录code
        that.data.loginMsg = '',//用于登录检查过期SessionTimeOut

        that.connectionTimeout('授权登录成功');

        that.getElementsCounts();//获取用户订单、购物车数量
        that.getDiscountCard();//获取优惠券数量
      } else {
        that.connectionTimeout('登陆失败');
      }
    });
  },

  //------------------显示购物车、订单等数量----------------------
  getElementsCounts: function() {
    let that = this;
    let isAuthorization = that.data.isAuthorization
    let rdSession = wx.getStorageSync('rd_session');
    console.log('getElementsCounts:显示购物车、订单等数量');
    let data = {'rdSession': rdSession};//请求参数
    if (isAuthorization) {
      http.getReq('/weixin/personal/getElementsCounts',data, function (res) {
        console.log(res);
        if (res.ret) {

          that.data.personOrderInfo = res.data.personOrderInfo; //用户订单信息
          that.data.pesonalCartInfo = res.data.pesonalCartInfo; //用户购物车信息
          that.data.personalInviteInfo = res.data.personalInviteInfo; //用户分享相关信息（订单＼用户）
          that.data.zjuserfxfee = res.data.zjuserfxfee; //用户累计收益
          that.data.customerServicePhone = res.data.customerServicePhone;//客服电话

          let cartCount = res.data.pesonalCartInfo.count; //购物车数量

          if (cartCount > 0) { //购物车项显示红点
            wx.showTabBarRedDot({
              index: 1
            })
          } else { //购物车项隐藏红点
            wx.hideTabBarRedDot({
              index: 1
            })
          }

          //购物车数量
          that.data.cartCount = cartCount
        }
      });

    }
  },


  //-------登陆初始化动画--------------
  loginAnimation: function() {
    if (this.data.loginCode === '' ){
      this.checkAndRefreshCode();
    }
    let animation = wx.createAnimation({
      duration: 200,
      timingFunction: 'ease',
      delay: 0
    })
    this.animation = animation;
    animation.height('100%').opacity(1).step();
    this.data.animationData = animation.export();
    this.data.showLogin = true;
    // wx.hideTabBar();
  },

  //--------------------关闭/登陆 动画----------------------------------
  closeLoginAnimation: function(e) { //触发获取用户信息的button 回调有userInfo
    console.log(e);
    let [msg, btnType, isAuthorization, that, detial] = ['', e.currentTarget.dataset.type, '', this, '']
    if (btnType != 'login') { //非登录按钮
      isAuthorization = false;
      msg = '取消登陆';
    } else { //登录
      let errMsg = e.detail.errMsg; //授权信息
      //授权成功没有授权弹窗，直接返回用户信息，携带e.detail.errMsg=getUserInfo:ok
      if (errMsg == 'getUserInfo:ok' && btnType == 'login') { //授权成功
        isAuthorization = true; //需要登录成功后授权
        // detial = e.detail;//用户基本信息-用于登录
        that.userLogin();
        wx.setStorageSync('userInfo', e.detail.userInfo); //用户信息保存到本地
        that.globalData.userInfo = e.detail.userInfo;
        msg = '登陆成功';
      } else { //拒绝授权
        isAuthorization = false;
        that.getLoginCode();//获取登录code
        msg = '登录失败，请您重新授权登录'
      }
    }

    that.data.isAuthorization = isAuthorization;
    that.data.showLogin = false; //关闭登录窗口

    //弹出提示信息
    that.connectionTimeout(msg);

    let animation = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease',
      delay: 200
    })

    this.animation = animation;
    animation.height(0).step();
    this.data.animationData = animation.export();

  },
  getToBuy: function(e) { //是否立即购买
    // 判断是否有商品下标(商品列表)
    let that = this;
    //let pindex = event.currentTarget.dataset.pindex;//商品列表下标
    let addtype = e.currentTarget.dataset.type; //判断是否是加入购物车
    let toBuy = false;
    ////判断是加入购物车还是立即购买---  ----设置按钮状态
    if (addtype == 'add') {
      toBuy = false;
    } else {
      toBuy = true;
    }
    that.data.toBuy = toBuy;
  },
  //--------------点击购物车按钮弹窗（加载商品和购买动作）---------------------------------
  addmessage: function(that) { //加入购物 车并选择购买商品信息
    let appThis = this;

    //初始化商品变量
    appThis.data.itemId = '';
    appThis.data.skuId = '';
    appThis.data.count = 1;
    appThis.data.stock = 0;

    //appjs中的初始化数据赋值------------------------------------
    appThis.data.chooseAttrids = []; //置空被选中的属性
    appThis.globalData.product = that.data.product;
  },
  getStock: function(that) {
    let appThis = this;
    let product = that.data.product;
    let productId = product.id;
    //----------------------------更新总库存和sku----------------------------

    let data = { 'productId': productId };//请求参数

    http.getReq('/weixin/item/getStock', data, function (res) {
      console.log(res);
      appThis.data.cartStock = res.stock;//购物车数量
      product.stock = res.stock;//商品总库存
      if (res.skus != null) {//商品sku库存
        product.skus = res.skus;
      } else {
        product.skus = [];
      }
      console.log('刷新后库存stock--' + product.stock);
    });
  },

  getSkuValue: function(product) { //获取商品sku
    let skus = product.skus;
    let prices = [];
    let skuAttrsObjs = [];
    let distAttrs = [] //所有分组展示信息[{name:"",value:[{},{}]},{name:"",value:[{},{}]}]    
    let skuTitles = [];
    let appThis = this;
    //--------判断有无skus----------------------------------------------
    if (skus.length > 0) {
      //取出所有属性值-----------------------------------------------------
      for (let i = 0; i < skus.length; i++) {
        prices.push(skus[i].price);
        let skuAttrs = skus[i].skuAttrs;
        if (skuAttrs.length >= 1) {
          for (let j = 0; j < skuAttrs.length; j++) {
            let attrObj = skuAttrs[j]
            skuAttrsObjs.push(attrObj); //将所有attrs取出
          }
        }
      }
      console.log(skuAttrsObjs);
      //skuAttrsObjs分组-----------属性分组[{name:"",value:[{},{}]},{name:"",value:[{},{}]}] 
      //name 对应 attrTitle value对应属性值

      let distAttrObj = {} //分组对象 distAttrObj.name='' distAttrObj.value[]
      distAttrObj.value = [] //存属性值信息
      let zcAttr = {} //暂存属性值 distAttrObj.value[]中对象包括 id 、attrValue、statu
      let names = ""; //存储name 数组

      if (skuAttrsObjs.length > 0) { //sku长度 > 0
        //第一次存储distAttrs数据
        distAttrObj.name = skuAttrsObjs[0].attrTitle; //分组标题
        distAttrObj.hasSelect = false; //同级是否已经有被选的选项
        zcAttr.id = skuAttrsObjs[0].id; //id （需要传递的值）
        zcAttr.attrValue = skuAttrsObjs[0].attrValue; //attrValue（展示的值）
        zcAttr.statu = 1; //状态
        distAttrObj.value.push(zcAttr);
        distAttrs.push(distAttrObj);
        names = distAttrs[0].name;

        for (let j = 0; j < distAttrs.length; j++) {
          console.log("distAttrs.length:" + distAttrs.length)
          for (let i = 1; i < skuAttrsObjs.length; i++) { //skuAttrsObjs从第一个开始
            if (skuAttrsObjs[i].attrTitle != distAttrs[j].name && names.lastIndexOf(skuAttrsObjs[i].attrTitle) < 0) { //属性名和name数组不包含属性名，distAttrs添加
              //初始化存储属性-----------------------------------------------------------------
              let distAttrObj1 = {} //分组对象 distAttrObj.name='' distAttrObj.value[]
              distAttrObj1.value = [] //存属性值信息
              let zcAttr1 = {} //暂存属性值 distAttrObj.value[]中对象包括 id 、attrValue、statu
              distAttrObj1.value = []; //初始化--存放不同的sku属性
              //-----------------------添加分组信息--------------------------------------------
              distAttrObj1.name = skuAttrsObjs[i].attrTitle;
              distAttrObj1.hasSelect = false; //同级是否已经有被选的选项
              zcAttr1.id = skuAttrsObjs[i].id;
              zcAttr1.attrValue = skuAttrsObjs[i].attrValue; //attrValue（展示的值）
              zcAttr1.statu = 1; //状态
              distAttrObj1.value.push(zcAttr1);
              distAttrs.push(distAttrObj1);

            } else { //名称相等比对value[]中的id
              let zcAttr2 = {} //暂存属性值 distAttrObj.value[]中对象包括 id 、attrValue、statu
              for (let s = 0; s < distAttrs.length; s++) {
                if (distAttrs[s].name == skuAttrsObjs[i].attrTitle) { //循环对比，若属性标题（时间等）
                  let distAttrsValues = distAttrs[s].value;
                  let add = true;
                  for (let v = 0; v < distAttrsValues.length; v++) { //对比属性值id
                    if (skuAttrsObjs[i].id == distAttrsValues[v].id) { //若相等则不添加
                      add = false;
                    }
                  }
                  if (add) { //添加distAttrs 属性中的value
                    zcAttr2.id = skuAttrsObjs[i].id;
                    zcAttr2.attrValue = skuAttrsObjs[i].attrValue; //attrValue（展示的值）
                    zcAttr2.statu = 1; //状态
                    distAttrs[s].value.push(zcAttr2);
                  }
                  break;
                }
              }
            }
            for (let n = 0; n < distAttrs.length; n++) {
              if (names.lastIndexOf(distAttrs[n].name) < 0) {
                names = names + "," + distAttrs[n].name;
              }
            }
          }
        }
      }
    }
    console.log("最终得到：" + distAttrs.length);
    if (distAttrs.length == 1){
      console.log('sku属性长度为1');
      let attrValues = distAttrs[0].value;
      for (let a = 0; a < attrValues.length; a++) {
        for (let s = 0; s < skus.length; s++) {
          if (attrValues[a].id == skus[s].attrListIds && skus[s].stock < 1){//库存小于1 改变其属性状态值
            attrValues[a].statu = 0;
          }
        }
      }
      distAttrs[0].value = attrValues;
    }
    appThis.data.skus = skus;
    appThis.data.skuTitles = skuTitles;
    appThis.data.distAttrs = distAttrs;
    appThis.data.stock = product.stock
    //--------------6.20修改部分
    console.log(distAttrs);
    //最终得到的distAttrs 中的sku长度，长度为1时设为默认
    for (let d = 0; d < distAttrs.length; d++) {
      if (distAttrs[d].value.length == 1) {
        distAttrs[d].value[0];
        let valObj = {};
        valObj.haveUnionSku = true; //属性下标
        valObj.attrindex = d; //属性下标
        valObj.itemindex = 0; //属性值下标
        valObj.val = distAttrs[d].value[0].id; //属性值id
        appThis.selectValue(valObj); //默认点击选中该属性
      }
    }
    //--------------6.20修改部分
    console.log("product.stock:" + product.stock);
  },
  unAddMessage: function() { //取消添加商品信息
    this.data.isshow = false;
    // this.data.opMask = 0;
    //-------------初始化数据---------------------------
    this.data.skus = [];
    this.data.distAttrs = [];
    this.data.chooseAttrids = [];
    this.data.itemId = '';
    this.data.skuId = '';
    this.data.count = 1;
    this.data.stock = 0;
    this.data.itemPrice = 0;//商品显示价格
    this.data.itemImg = '';//商品显示价格
  },
  //---------------------------点击选择商品属性---------------------------------
  selectValue: function(e) {
    console.log(e);
    let [that, attrindex, itemindex, val] = [this, '', '', ''];
    if (e.haveUnionSku) { //具有唯一sku默认选中
      attrindex = e.attrindex; //属性下标
      itemindex = e.itemindex; //属性值下标
      val = e.val; //属性值id
    } else {
      attrindex = e.currentTarget.dataset.attrindex; //属性下标
      itemindex = e.currentTarget.dataset.itemindex; //属性值下标
      val = e.currentTarget.dataset.val; //属性值id
    }
    //获取已选节点
    let chooseAttrids = that.data.chooseAttrids;
    console.log("已选择chooseAttrids--" + chooseAttrids);
    //判断是否已被选中--更改选中状态-----------------------------
    /**
     * 属性分组distAttrs
     */
    let distAttrs = that.data.distAttrs;
    let attrValues = distAttrs[attrindex].value;
    if (attrValues[itemindex].statu == 2) { //已选中
      attrValues[itemindex].statu = 1
      distAttrs[attrindex].hasSelect = false; //取消被选状态
      chooseAttrids[attrindex] = ''; //备选状态置空

    } else { //未选中
      distAttrs[attrindex].hasSelect = true; //该级别改变选中状态
      chooseAttrids[attrindex] = val; //加入已选属性数组
      for (let d = 0; d < attrValues.length; d++) { //更改其他级别属性
        if (d == itemindex) {
          attrValues[d].statu = 2
        } else {
          attrValues[d].statu = 1
        }
      }
    }
    distAttrs[attrindex].value = attrValues;
    that.data.chooseAttrids = chooseAttrids;
    //---------------- step 1  设置为选择属性中不可选节点状态------------------------

    let all_ids = that.filterAttrs(chooseAttrids); //符合条件的所有属性值
    /**
     * 未选择的属性组other_notsel_attr(结构同distAttrs)
     */
    let other_notsel_attr = []; //所有未选属性
    /**
     * 所有已选规格属性sel_goods_attr(结构同distAttrs)
     */
    let sel_goods_attr = []; //所有已选规格属性

    for (let i = 0; i < distAttrs.length; i++) {
      if (distAttrs[i].hasSelect) { //已选
        sel_goods_attr.push(distAttrs[i]);
        continue;
      } else {
        other_notsel_attr.push(distAttrs[i]);
      }
    }

    //设置未选属性可选状态
    for (let j = 0; j < other_notsel_attr.length; j++) {
      let attrValue = that.setBlock(other_notsel_attr[j], all_ids); //选择属性中的不可选节点
      other_notsel_attr[j].value = attrValue;
    }
    console.log('未选属性状态值');
    console.log(other_notsel_attr);
    //------------step 2 设置已选节点的同级节点是否可选---------------------------

    for (let s = 0; s < sel_goods_attr.length; s++) {
      let attrValue2 = that.update_2(sel_goods_attr[s]);
      sel_goods_attr[s].value = attrValue2;
    }
    console.log('已选属性状态值');
    console.log(sel_goods_attr);

    //-------------设置distAttrs 属性值-------------------------------------------

    for (let d = 0; d < distAttrs.length; d++) {
      //比对name 更改未选属性状态值
      for (let j = 0; j < other_notsel_attr.length; j++) {
        if (other_notsel_attr[j].name == distAttrs[d].name) {
          distAttrs[d] = other_notsel_attr[j];
        }
      }
      for (let s = 0; s < sel_goods_attr.length; s++) {
        if (sel_goods_attr[s].name == distAttrs[d].name) {
          distAttrs[d] = sel_goods_attr[s];
        }
      }
    }
    //更新属性值
    that.data.distAttrs = distAttrs;
    //--------------------拼接被选中属性值---------------------------
    let chooseIdStr = ''

    for (let i = 0; i < chooseAttrids.length; i++) {
      if (chooseAttrids[i] == undefined || chooseAttrids[i] == '') {
        continue;
      }
      if (chooseIdStr == '') {
        chooseIdStr = chooseAttrids[i];
      } else {
        chooseIdStr = chooseIdStr + ';' + chooseAttrids[i];
      }
    }

    console.log('被选中属性值chooseIdStr---' + chooseIdStr);

    // 获取itemImg sku 小图；
    that.getSkuImg(chooseIdStr);
    //-----------------更改价格和库存--------------------------
    let hasSku = false; //是否存在skuid
    let sku_list = this.globalData.product.skus;
    for (let s = 0; s < sku_list.length; s++) {
      if (sku_list[s].attrListIds == chooseIdStr) {
        that.data.skuId = sku_list[s].id; //skuId
        that.data.itemId = sku_list[s].itemId; //交互---商品id
        that.data.count = 1;
        that.data.stock = sku_list[s].stock; //商品库存
        that.data.itemPrice = sku_list[s].price; //商品库存
        hasSku = true;
      }
    }
    if (!hasSku) {
      that.data.stock = that.globalData.product.stock; //商品库存
      that.data.skuId = ''; //商品skuid
      that.data.itemId = ''; //商品itemId
      that.data.itemPrice = 0; //商品显示价格
    }
    console.log("skuid:" + that.data.skuId);
    console.log("itemId:" + that.data.itemId); 
    console.log("stock:" + that.data.stock);
    console.log("count:" + that.data.count);
    console.log("itemPrice:" + that.data.itemPrice);
    console.log("itemImg:" + that.data.itemImg);

  },
  /**
   * 获取sku小图
   */
  getSkuImg: function (chooseAttrids){
    let that = this;
    let product = that.globalData.product;
    let skuAttrs = product.skuAttrs;
    let findItemImg = false;
    console.log('获取sku小图');
    console.log('chooseAttrids--' + chooseAttrids);

    // 最小属性单位
    if (skuAttrs.length > 0){
      for (let s = 0; s < skuAttrs.length;s++) {
        //判断带有小图的单位是否包含在已选属性id
        if (chooseAttrids.indexOf(skuAttrs[s].attrid) > -1){
          console.log('skuAttrs[s].attrid--' + skuAttrs[s].attrid);
          console.log('找到匹配的sku小图' + skuAttrs[s].imgUrl);
          that.data.itemImg = skuAttrs[s].imgUrl;
          findItemImg = true;
          break;
        }
      }
      if (findItemImg === false){
        that.data.itemImg = '';
      }
    }
  
  },
  //所有可能的路径
  //------------------获取所有包含指定节点的路线--------------------------
  filterProduct: function(chooseAttrids) { //ids
    let that = this;
    let allAttrids = []; //所有包含所选元素的节点路线
    //sku_list => sku
    let sku_list = this.globalData.product.skus;
    for (let s = 0; s < sku_list.length; s++) { //attrListIds
      if (sku_list[s].stock < 1) { //过滤掉库存小于1 的路线
        continue;
      }
      let attrListIds = ';' + sku_list[s].attrListIds + ';'
      let _all_ids_in = true;
      for (let c = 0; c < chooseAttrids.length; c++) {
        if (chooseAttrids[c] == "" || chooseAttrids[c] == undefined) {
          continue;
        }
        if (attrListIds.indexOf(';' + chooseAttrids[c] + ';') == -1) {
          _all_ids_in = false;
          break;
        }
      }
      if (_all_ids_in) {
        allAttrids.push(sku_list[s]); //所有符合条件的sku信息
      }
    }
    return allAttrids;
  },
  /**
   * 1. 获取 经过已选节点 所有线路上的全部节点
   * 2. 根据已经选择得属性值，得到余下还能选择的属性值
   */
  filterAttrs: function(chooseAttrids) {
    let that = this;
    console.log('filterAttrs');
    let allAttrids = that.filterProduct(chooseAttrids); //所有符合条件的路线
    console.log('所有符合条件的路线');
    console.log(allAttrids);
    let result = [];
    for (let i = 0; i < allAttrids.length; i++) {
      result = result.concat(allAttrids[i].attrListIds.split(';'));
    }
    console.log('所有符合条件的属性值array');
    console.log(result);
    return result;
  },
  /**
   * 更改备选状态 (未选属性行元素，符合条件的所有属性值)
   */
  setBlock: function(goods_attr, all_ids) {

    let attrValue = goods_attr.value;
    for (let a = 0; a < attrValue.length; a++) {
      //查验符合条件的属性值是否包含（attrValue[a]）
      if (all_ids.indexOf(attrValue[a].id) == -1) { //没有
        attrValue[a].statu = 0;
      } else {
        if (attrValue[a].statu != 2) {
          attrValue[a].statu = 1;
        }
      }
    }
    return attrValue;
  },

  /**
   * 设置已选节点的同级节点是否可选(已选分组行元素，所有已选id)
   */
  update_2: function(goods_attr) {
    let that = this;
    let chooseAttrids = that.data.chooseAttrids;
    let attrValue = goods_attr.value;
    let changedValue = [];
    //找到被选中的元素值
    for (let a = 0; a < attrValue.length; a++) {
      if (attrValue[a].statu == 2) {
        /**
         * 剔除已选中元素的chooseAttrids
         */
        let chooseAttrids2 = that.del_array_val(chooseAttrids, attrValue[a].id);
        let all_ids = that.filterAttrs(chooseAttrids2); //筛选返回所有可选属性值
        changedValue = that.setBlock(goods_attr, all_ids);
      }
    }
    return changedValue;
  },
  /**
   * 把被选中的属性值从全部被选中数组中剔除并返回新数组
   */
  del_array_val: function(chooseAttrids, attrId) {
    let newArr = [];
    for (let c = 0; c < chooseAttrids.length; c++) {
      if (chooseAttrids[c] == undefined || chooseAttrids[c] == '') {
        continue;
      } else {
        if (chooseAttrids[c] != attrId) {
          newArr.push(chooseAttrids[c]);
        }
      }
    }
    return newArr;
  },
  addCount: function(e, that) { //增加商品数量
    console.log(e);
    console.log(that.data.stock);
    let inputCount = e.target.dataset.count;
    let product = this.globalData.product;
    let count = this.data.count; //商品数量
    let stock = this.data.stock;
    let skus = this.globalData.product.skus;
    //限购设置
    let isLimited = this.globalData.product.isLimited;
    let limitedNum = this.globalData.product.limitedNum; //限购数量
    //----------判断有无sku-----------------------------------------------
    if (skus.length > 0) {
      let chooseAttrids = this.data.chooseAttrids;
      let chooseAttridsStr = '';
      //-----拼接已选择的商品id------------------------
      for (let i = 0; i < chooseAttrids.length; i++) {
        if (chooseAttridsStr == '') {
          chooseAttridsStr = chooseAttrids[i]
        } else {
          chooseAttridsStr = chooseAttridsStr + ';' + chooseAttrids[i]
        }
      }
      console.log('chooseAttridsStr:' + chooseAttridsStr);

      let find = false;
      //-------------判断已经选择的chooseAttridsStr是否与sku 中的attrid相等
      for (let i = 0; i < skus.length; i++) {
        if (chooseAttridsStr.lastIndexOf(skus[i].attrListIds) < 0) { //不包含skus[i].attrListIds
          find = false; //不包含
          continue;
        } else {
          find = true;
        }

        //变更状态----------------------------------------------------------

        if (find) { //找到了匹配的
          stock = skus[i].stock;
          if (inputCount < stock) { //当前显示数量小于库存
            count = parseInt(inputCount) + 1;
            break;
          } else {
            util.showToast('库存不足', 1000, 'none', function () { });
            count = stock;
            break;
          }
        }
      }
      if (!find) { //如果没有找到
        count = parseInt(inputCount) + 1;
        stock = stock;
      }
    } else { //没有sku 的状态 获取商品数量

      stock = product.stock;
      let msg = '';
      let compareNum = 0; //用于与用户输入比较
      if (isLimited == '1') { //限购
        compareNum = limitedNum;
        msg = '此商品为限购商品，限购数量为' + limitedNum
      } else {
        compareNum = stock
        msg = '库存不足';
      }
      if (inputCount < compareNum) {
        count = parseInt(inputCount) + 1
      } else { //大于等于商品库存数量
        count = compareNum
        util.showToast(msg, 1000, 'none', function () { });
      }
    }
    this.data.count = count;
    this.data.stock = stock;
  },
  minsCount: function(e, that) {
    console.log("minsCount:" + e);
    let appThis = this
    let inputCount = e.target.dataset.count;

    console.log(inputCount);
    if (inputCount > 1) {
      appThis.data.count = parseInt(inputCount) - 1;
    } else {
      util.showToast('购买数量不能小于1', 1000, 'none', function () { });
      appThis.data.count = 1;
    }
  },
  changeCount: function(e, that) {
    console.log(e);
    let inputcount = e.detail.value;
    console.log(inputcount);
    let stock = this.data.stock;
    let count = this.data.count;
    let product = this.globalData.product;
    //限购设置
    let isLimited = this.globalData.product.isLimited;
    let limitedNum = this.globalData.product.limitedNum; //限购数量
    let skus = product.skus;

    //判断输入商品数量是否小于1--------------------------------
    if (inputcount < 1) {
      util.showToast('购买数量不能小于1', 1000, 'none', function () { });
      count = 1;
    } else {
      //---------------判断有无skus,改变商品库存---------------
      if (skus.length > 0) {
        if (stock <= 0) { //初始化库存为0
          count = inputcount;
        } else {
          if (inputcount > stock) { //是否小于库存
            util.showToast('库存不足', 1000, 'none', function () { });
            count = stock;
          } else {
            count = inputcount;
          }
        }
      } else {
        stock = product.stock;
        let msg = '';
        let compareNum = 0; //用于与用户输入比较
        if (isLimited == '1') { //限购
          compareNum = limitedNum;
          msg = '此商品为限购商品，限购数量为' + limitedNum
        } else {
          compareNum = stock
          msg = '库存不足';
        }
        if (inputcount <= compareNum) {
          count = inputcount
        } else {
          count = compareNum
          util.showToast(msg, 1000, 'none', function () { });
        }
      }
    }

    this.data.count = count;
    this.data.stock = stock;
  },
  validateSKU: function(that) { //验证sku
    let skus = that.data.product.skus;
    let distAttrs = that.data.distAttrs;
    let chooseAttrids = that.data.chooseAttrids; //已选商品id拼接
    let addcart = true; //是否满足条件 ---可以加入购物车

    //------------判断有无sku-------------------------------------
    if (skus.length > 0 && distAttrs.length > 0) {
      //----------------检查商品信息-------------------------------
      if (chooseAttrids.length > 0) {
        for (let i = 0; i < distAttrs.length; i++) {
          console.log("chooseAttrids[i]" + chooseAttrids[i]);
          if (chooseAttrids[i] == '' || chooseAttrids[i] == undefined) {
            addcart = false;
            util.showToast("请选择 " + distAttrs[i].name, 1000, 'none', function () { });
          
            break;
          }
        }
      } else {
        util.showToast("请选择 " + distAttrs[0].name, 1000, 'none', function () { });
        addcart = false;
      }
    } else {
      addcart = true;
    }
    this.data.addcart = addcart;
    return addcart;
  },
  addCart: function(e, that) { //点击加入购物车
    // //------------------------判断session是否过期-------------------------------
    
    console.log("加入购物车" + e.target.dataset.pid);
    let appThis = this;
    //-------------是否有推荐人--------------------------------
    let inviter = that.data.inviter;
    //-------------验证判断------------------------------------
    let addType = e.target.dataset.type; //是否加入购物车 or 立即购买 add /submit
    let addcart = appThis.data.addcart //是否满足条件 ---可以加入购物车

    //-------------立即购买所需参数----------------------------
    let itemId = that.data.product.id; //商品id
    let skuId = that.data.skuId;
    let count = that.data.count; //加入购物车的数量
    let rdSession = wx.getStorageSync('rd_session');

    //setTimeout(function () {
    let isAuthorization = appThis.data.isAuthorization;
    if (isAuthorization) {
      //店铺信息
      let [shopuid, shopInfo] = ['', wx.getStorageSync('shopInfo')];
      shopuid = shopInfo.shopuid || '';
      console.log('addcart:shopuid--' + shopuid);
    
      if (addcart) {
        // let makeAnimation = true;
        //-----------可以加入购物车--------------------------------

        //请求参数
        let data = {
          'itemId': itemId,
          'rdSession': rdSession,
          'skuId': skuId,
          'count': count,
          'inviter': inviter,
          'shopuid': shopuid
        };

        if (addType == 'add') {
          console.log("skuid:" + skuId);
          console.log("itemId:" + itemId);
          console.log("count:" + appThis.data.count);
          //-------------向后台传递data----------------------------
          http.getReq('/weixin/cart/add', data, function (res) {
            console.log(res);
            if (res.ret) { //添加购物车成功
              util.showToast('已加入购物车', 500, 'none', function () { });
              appThis.getElementsCounts(); //查看购物车状态（购物车商品数量）
            } else { //加入购物车失败
              if (res.msg == 'SessionTimeOut') { //session失效
                console.log('SessionTimeOut');
              } else { //库存不足
                util.showToast(res.msg, 500, 'none', function () { });
              }
            }
            console.log("this.global.product:" + appThis.globalData.product);
          });

          appThis.data.count = 1;
        } else if (addType == 'submit') { //立即购买
          //-------------向后台传递data----------------------------
          console.log('skuId--' + skuId);
          http.getReq('/weixin/cart/ConverToProduct', data, function (res) {
            console.log(res);
            if (res.ret) {
              //-----返回的商品信息添加到cartProducts------
              let cartProducts = [];
              cartProducts.push(res.data);
              appThis.data.cartProducts = cartProducts
              wx.navigateTo({
                url: "/pages/product/pages/order/order",
              })
            } else {
              console.log('待付款订单跳转失败');
              //--------------重新登陆-----------------
              if (res.msg == "SessionTimeOut") {
                console.log('SessionTimeOut');
              }
            }
          });
        }
        if (e.target.dataset.type == 'submit') { //确认订单页
          appThis.data.toBuy = true
        } else {
          appThis.data.toBuy = false
        }
     
      } else {
        return;
      }
    } else {
      util.showToast('您还未登录,请先登录', 1000, 'none', function () {
        appThis.data.isAuthorization = false;
        appThis.loginAnimation();
        return;
       });
    }
  },

  cancelShare: function() { //取消分享
    console.log("取消分享")
    var animation = wx.createAnimation({
      duration: 500,
      timingFunction: "ease",
      delay: 0
    })
    this.animation = animation
    animation.height(0).step();
    this.data.animationData = animation.export();
    this.data.isshow = false;
  },

  toPayPage: function(that) { //待付款订单
    let appThis = this;
    let cartProducts = that.data.cartProducts; //待付款订单列表
    let totalCount = that.data.totalCount; //商品总额
    if (cartProducts) {
      console.log(cartProducts);
    }
    //过滤被选商品
    let newList = [];
    for (let i = 0; i < cartProducts.length; i++) {
      if (cartProducts[i].isSelect == 1) {
        newList.push(cartProducts[i]);
      }
    }
    appThis.data.cartProducts = newList;
    appThis.data.totalCount = totalCount;
    wx.navigateTo({
      url: '/pages/product/pages/order/order',
    })
  },

  //---------------------------------支付-----------------------------
  wxPay: function(e, that) { //提交订单
    
    let appThis = this;
    //-----判断是否有地址------------
    //let hasAddress = that.data.hasAddress;
    let [sendMessage, hasAddress] = [that.data.sendMessage, that.data.hasAddress]; //是否短信通知，是否有地址
    console.log('是否发送短信sendMessage：' + sendMessage);
    if (!hasAddress) {
      util.showToast('请新建收货地址', 1000, 'none', function () { });
      return;
    }
    console.log("wxPay");
    console.log(that);
    //------设置支付按钮状态
    appThis.data.ispay = true;
    let formId = e.detail.formId; //formId用于发送模板消息
    let cartProducts = that.data.cartProducts; //待付款商品列表
    let rd_session = wx.getStorageSync('rd_session');
    let defaultAddress = that.data.defaultAddress; //默认地址
    let orderId = that.data.orderId; //判断订单是否有orderId
    let buyerMemo = that.data.buyerMemo;//买家留言
    let submitOrderNoPay = that.data.submitOrderNoPay;//只提交订单不支付
    //存formid用于发送模板推送消息
    if (submitOrderNoPay){
      appThis.getFormId(e);
    }
    console.log(cartProducts);
    console.log(rd_session);
    console.log(defaultAddress);
    console.log('表单id:', formId);

    if (orderId == undefined || orderId == '' || orderId == null) {//没有订单调提交订单支付接口
      //提交表单
      console.log('buyerMemo:' + buyerMemo);
      appThis.submitOrder(cartProducts, rd_session, defaultAddress, formId, buyerMemo,submitOrderNoPay);
    } else {//有订单号
      // if (!submitOrderNoPay){//有订单号，无需提交订单
        console.log("orderId" + orderId);
        appThis.payByOrderId(formId, orderId, rd_session)
      // }
    }
    //---------------根据订单是否支付成功发送模板消息---------------

  },
  //提交订单
  submitOrder: function (cartProducts, rd_session, defaultAddress, formId, buyerMemo, submitOrderNoPay) {
    console.log('submitorder表单id' + formId);
    let appThis = this;
    //店铺信息
    let [shopuid, shopInfo] = ['', wx.getStorageSync('shopInfo')];
    if (shopInfo.shopuid != undefined && shopInfo.shopuid != null && shopInfo.shopuid != '') {
      shopuid = shopInfo.shopuid;
    }

    //请求参数
    let data = {
      'productList': cartProducts,
      'rdSession': rd_session,
      'buyerAddress': defaultAddress,
      'shopuid': shopuid,
      'buyerMemo': buyerMemo
    };

    if (submitOrderNoPay){//只提交订单不付款
      http.getReq('/weixin/order/submitOrderNoPay', data, function (res) {
        console.log(res);
        console.log("提交订单结果" + res.ret);

        //重定向到全部订单
        setTimeout(function () {
          wx.redirectTo({
            url: '/pages/user/pages/orders/orders?activeIndex=1&statusOri=10',//跳转至待付款订单列表
          })
        }, 100)
      });

    }else{
      http.getReq('/weixin/order/submitOrder', data, function (res) {
        console.log(res);
        console.log("提交订单结果" + res.ret);
        let ret = res.ret;
        let [prepay_id, orderId] = ['', ''];
        if (ret) {
          console.log('订单提交成功表单id' + formId);
          prepay_id = res.data.prepay_id;
          orderId = res.data.orderId;
          console.log('submitOrder返回订单号：' + orderId);
          //提交订单成功获取支付接口
          console.log('提交订单成功获取支付接口');
          console.log(res.data.timeStamp);
          //微信支付
          wx.requestPayment({
            timeStamp: res.data.timeStamp,
            nonceStr: res.data.nonceStr,
            package: res.data.package,
            signType: 'MD5',
            paySign: res.data.paySign,
            success: function (res) {
              console.log('订单requestPayment成功表单id' + formId);

              util.showToast('绑定成功', 1500, 'success', function () { 
                //修改订单状态 发送模板消息
                appThis.payCallBack(orderId, rd_session);
                //发送支付成功模板消息
                appThis.paySendTemp(true, formId, rd_session, orderId);
              });

            },
            fail: function (res) { //待付款订单
              console.log('订单requestPayment失败表单id' + formId);
              console.log(res);
              console.log("付款失败");
              util.showToast('付款失败', 1500, 'none', function () { 
                //支付失败的模板--待付款通知模板------------------------------------
                // appThis.paySendTemp(false, formId, rd_session, orderId);
                setTimeout(function () {
                  wx.redirectTo({
                    url: '/pages/user/pages/orders/orders?activeIndex=1&statusOri=10' //跳转到待付款订单列表
                  })
                }, 1000)
              });
             
            }
          })

        } else {
          if (res.msg !== 'reSubmit') {
            util.showToast('提交订单失败', 1000, 'none', function () { 
              //重定向到全部订单
              setTimeout(function () {
                wx.redirectTo({
                  url: '/pages/user/pages/orders/orders',
                })
              }, 1000)
            });
          }
        }

      });
   
    }
  },
  //根据订单编号支付商品
  payByOrderId: function(formId, orderId, rd_session) {
    let appThis = this;
    let data = {
      'orderId': orderId,
      'rdSession': rd_session,
    }
    //支付订单----------------------------------------------------------
    http.getReq('/weixin/order/payOrder', data, function (res) {
      //微信支付
      wx.requestPayment({
        timeStamp: res.data.timeStamp,
        nonceStr: res.data.nonceStr,
        package: res.data.package,
        signType: 'MD5',
        paySign: res.data.paySign,
        success: function (res) {
          console.log("支付成功");
          //支付成功弹窗
          util.showToast('支付成功', 1500, 'success', '');
          //修改订单状态 发送模板消息
          appThis.payCallBack(orderId, rd_session);
          //发送支付成功模板消息
          appThis.paySendTemp(true, formId, rd_session, orderId);

        },
        fail: function (res) { //待付款订单
          console.log(res);
          console.log("付款失败");
          util.showToast('付款失败', 1000, 'none', function () { 
            //支付失败的模板--待付款通知模板------------------------------------
            // appThis.paySendTemp(false, formId, rd_session, orderId);
          });
        },
        complete: function () {
          setTimeout(function () {
            wx.redirectTo({
              url: '/pages/user/pages/orders/orders',
            })
          }, 2000)
        }
      })
    });
  
  },
  backToHome: function(that) { //返回到首页
    //回到首页
    wx.switchTab({
      url: '/pages/home/home', //店铺id 、店铺名称 、分享标识
      success: function(e) { //跳转刷新
        let page = getCurrentPages().pop(); //强制刷新跳转页面，
        if (page == undefined || page == null) return;
        
      }
    })
  },
  //根据商品id跳转至商品详情页
  selectProductById: function(that) {
    let shopInfo = wx.getStorageSync('shopInfo');
    let shopuid = that.data.shopuid;
    if (shopInfo.shopuid){
       shopuid = shopInfo.shopuid;
    }
    console.log(shopInfo);
    console.log('?productId=' + that.data.productId + '&shopuid=' + shopuid);
    wx.navigateTo({
      url: that.data.pageUrl + '?productId=' + that.data.productId + '&shopuid=' + shopuid,
      success: function(res) {
        wx.hideToast();
      }
    })
  },
  //----------播放弹窗动画、遮罩层-------------------------
  makeAnimation: function() {
    let that = this;
    //初始化动画
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    // animation.translateY('100%').step()
    animation.translateY('100%').step()
    that.data.animationData = animation.export();
    that.data.opMask = 1;
    that.data.isshow = true;
    setTimeout(function() {
      animation.translateY(0).step()
      that.data.animationData = animation.export();
    }.bind(this), 50)
    //通过动画实例得export方法导出动画数据给自身得animation属性
    //调用一次export 方法后也会清除到之前得动画操作
  },
  cancelAnimation: function () {//收回弹窗、隐藏遮罩层
    let that = this;
    //初始化动画
    let animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation;
    animation.translateY('100%').step();
    that.data.animationData = animation.export();

    setTimeout(function() {
      animation.translateY(0).step();
      that.data.animationData = animation.export();
      that.data.isshow = false;
      that.data.showLogin =false;
    }.bind(this), 200)

    //通过动画实例得export方法导出动画数据给自身得animation属性
    //调用一次export 方法后也会清除到之前得动画操作
  },
  toCategoryPage: function(e) {
    console.log("toCategoryPage跳转更多分类");
    console.log(e);
    let catyindex = e.currentTarget.dataset.catyindex;
    wx.navigateTo({
      url: '/pages/home/pages/category/category?catyindex=' + catyindex
    })
  },
  //---------------------手机绑定-------------------------------
  //验证手机号码
  testPhone: function(e) {
    console.log('验证手机号码');
    console.log(e);
    //let that = this
    let [that, phoneNum, isPhone] = [this, e.detail.value, this.data.isPhone];
    //let phoneNum = e.detail.value;
    if (phoneNum.length >= 11) {
      if (!(/^1[34578]\d{9}$/.test(phoneNum))) {
        isPhone = false;
        util.showToast('手机号有误', 1500, 'none', function () { });
      } else {
        isPhone = true;
      }
    } else {
      isPhone = false;
    }
    that.data.isPhone = isPhone;
    that.data.phoneNum = phoneNum;
  },
  //获取验证码
  getPhoneCode: function(e, there) {
    console.log(e);
    console.log('手机号码：' + there.data.phoneNum);
    //let [that, phoneNum] = [this,there.data.phoneNum];
    let [that, phoneNum] = [this, there.data.phoneNum];
    http.getReq('/weixin/personal/getVerifyCode', {
      phoneNum: phoneNum
    }, function (res) {
      console.log('获取验证码回调')
      console.log(res);
      let codeNum = res.data
      that.data.codeNum = codeNum;
      if (res.ret) {
        that.data.getCode = true;
      } else {
        that.data.getCode = false;
        util.showToast(res.msg, 2000, 'none', function(){});//弹窗
      }
    });
  },

  //提交表单保存手机号
  savePhoneNum: function(e, that) {
    console.log(e);
    let [code, phoneNum, appThis, isPhone] = [e.detail.value.code, e.detail.value.phone, this, that.data.isPhone]
    let rdSession = wx.getStorageSync('rd_session');
    if (code.length == 4) {
      http.getReq('/weixin/personal/verifyPhoneNum', {
        phoneNum: phoneNum,
        rdSession: rdSession,
        code: code
      }, function (res) {
        console.log('绑定手机号回调')
        console.log(res);
        //隐藏绑定框isshow
        let [ret, msg] = [res.ret, res.msg];
        if (ret) { //验证通过

          util.showToast('绑定成功', 1000, 'success', function(){});

          wx.setStorageSync('isBindPhone', true) //已绑定手机
          appThis.data.isBindPhone = true; //已绑定
          appThis.data.isshow = false;

        } else {
          util.showToast(msg, 1000, 'none', function () {});

          appThis.data.isBindPhone = false; //已绑定
          appThis.data.isshow = true;
        }
        appThis.data.codeTime = 60;
        appThis.data.getCode = false;
      });
    } else {
      util.showToast('验证码输入不合法', 1000, 'none', function () { });
      return
    }
  },
  //----------------验证绑定手机号表单--------------------
  validateSavePhoneForm: function(e, that) {
    let appThis = this;
    let [code, isPhone, codeNum] = [e.detail.value.code, that.data.isPhone, appThis.data.codeNum];
    let validate = true;
    //验证手机号和验证码是否合法
    if (!isPhone) {
      util.showToast('手机号输入不合法', 1500, 'none', function () { });
      return false;
    }
    if (code.length != 4) {
      util.showToast('验证码输入不合法', 1500, 'none', function () { });
      return false;
    }
    if (codeNum != code) {
      util.showToast('验证码输入错误', 1500, 'none', function () { });
      return false;
    }
    return validate;
  },
  //手机预览商品缩略图
  previewImage: function(e) {
    let codeUrl = e.currentTarget.dataset.src;
    let scanQrCodeUrl = []
    scanQrCodeUrl.push(codeUrl);
    wx.previewImage({
      urls: scanQrCodeUrl,
    })
  },
  //设置店铺信息：
  setShopTitle: function() {
    console.log('设置店铺标题：');
    //获取本地的店铺信息------------------------------------------
    let shopInfo = wx.getStorageSync('shopInfo');
    //设置店铺标题：
    if (shopInfo.shopName) {
      wx.setNavigationBarTitle({ //设置首页店铺名称显示
        title: '咱 + ' + shopInfo.shopName
      })
    }

  },

  //------------------未开通服务提示----------------------
  unOpen: function() {
    util.showToast('该功能尚未开通，敬请期待~', 1500, 'none', function () { });
  },
  //--------------------消息提示----------------------------
  connectionTimeout: function(msg,time) {
    let defaultMsg = '网络异常，请稍后再试';
    util.showToast(msg || defaultMsg, time || 1500, 'none', function () { });
  },
  //图片加载失败出现错误时替换图片路径
  errImg: function (products, proIndex) {
    products[proIndex].itemimags[0].thumbImgs = this.data.defaultImgUrl;//修改成默认图片
    return products;
  },
  //获取formid
  getFormId: function (e) {
    let formId = e.detail.formId;
    if (formId != 'the formId is a mock one' && formId !=''){
      let formObj = {};
      formObj.formId = formId;
      formObj.expiryTime = parseInt(new Date().getTime() / 1000) + 604800 //计算7天后的过期时间时间戳;
      this.data.formIdPool.push(formObj);
    }
    console.log('formIdPool:' + this.data.formIdPool);
  },
 
  //获取用户绑定的真实姓名
  getUserName:function(){
    console.log('获取用户绑定的真实姓名');
    let that = this;
    let rdSession = wx.getStorageSync('rd_session');

    http.getReq("/weixin/withdraw/getRealName", {
      rdSession: rdSession
    }, function (res) {

      console.log(res);
      let hasRealName = res.data.hasRealName;//true/false
      let userName = '';
      if (hasRealName) {
        userName = res.data.realName;
      }
      that.data.hasRealName = hasRealName;//用户是否绑定真实姓名
      that.data.userName = userName;//用户真实姓名
    });
  },
  //设置用户授权状态
  setUserInfoScope:function(pageData){
    this.data.isAuthorization = pageData.data.userInfoScope;//用户信息授权
  },
  //设置地理位置信息
  setCityName: function (cityName) {
    console.log('setCityName-地理位置信息保存在本地');
    this.data.cityName = cityName || '北京';
    wx.setStorageSync("cityName", cityName || '北京');//保存到本地
  },
  //加载城市列表
  loadCityArray:function(){
    console.log('加载城市列表');
    let that = this;
    let cityName = that.data.cityName;
    console.log("cityName != '成都'--" + (cityName != '成都'));
    if (cityName != '成都'){//成都不需要加载城市列表
      http.getReq('/weixin/sys/ZjCity/list', {}, function (res) {
        console.log('返回城市列表');
        console.log(res);
        that.data.cityArray = res;
      });
    }
  },

  saveFormIdPool: function () {
    let that = this;
    //发送存储formIdPool
    let formIdPool = that.data.formIdPool;
    let rdSession = wx.getStorageSync('rd_session');
    console.log('一共获得' + formIdPool.length + '个formid');

    //回调中清空本地formIdPool
    http.getReq('/weixin/formid/save', {
      rdSession: rdSession,
      formIdPool: formIdPool
    }, function (res) {
      console.log(res);
      that.data.formIdPool = [];
    });
  },
  //
  /**
   * 改变选择城市
   */
  onCityChange:function(e){
    let that = this;
    let [cityArray, index] = [that.data.cityArray, e.detail.value];
    that.data.cityName = cityArray[index];
  },

  checkAndRefreshCode: function () {//刷新code

    console.log('');
    let that = this;
    that.getLoginCode();//获取登录code

    let refreshCodeTask = setInterval(function () {
      let isAuthorization = that.data.isAuthorization;
      let isShowAD = that.data.isShowAD;
      if (isAuthorization === false && (isShowAD === false || isShowAD === true)) {//未登录
        that.getLoginCode();//获取登录code
      } else {//已登陆
        console.log('结束刷新code任务');
        clearInterval(refreshCodeTask);
      }
    }, 290000)//4.8分钟刷新一次
  },

  getLoginCode: function () {//获取登录code 计时器每5分钟运营一次

    let that = this;
    wx.login({
      success: function (res) {
        console.log('登录code'+res.code);
        that.data.loginCode = res.code
      },
      fail: function (res) {
        console.log('获取登录code失败' + res);
      }
    })

  },
  getDiscountCard:function(){//获取用户优惠券
    console.log('获取用户优惠券');
    let that = this;

    http.getReq('/weixin/couponInfo/list', {
      rdSession: wx.getStorageSync('rd_session')
    }, function (res) {
      console.log(res);
      if (res.ret) {//优惠券
        that.data.discountCardList = res.data.data;
      }
    });
    
  },
  cancelSettingBox: function () { //关闭设置提示窗
    this.data.showSettingBox = false;
  },
  showSettingBox: function () {//打开设置提示窗
    this.data.showSettingBox = true;
  },
  //发送支付模板消息
  paySendTemp: function (ret,formId, rd_session, orderId){

    let [template_id, page,requestUrl] = ['','',''];
    //支付是否成功
    if (ret){
      template_id = 'W3WizWfcMElByn9iRKpiY8t7fFkxyl9opBLUSOiN5ng';//  'vozG3chDxaKJ4cOnzr2LZAhXwgZF4mQ4XM_6DsNfXow';//   
      page = 'pages/user/orders/orders?checkOrders=1';
      requestUrl = '/weixin/msg/payOkSend';
    }else{
      template_id = '80woXa3XellcOG2096S6E7k_DyFKi--9ApMubORtNf0';// 'lePzgGRMbxNu8qKatPL7S1Fm3LmwG0-mUPq3NjpybMU'; // 
      page = 'pages/product/order/order?orderId=' + orderId; //跳转到待付款订单页面
      requestUrl = '/weixin/msg/payFailSend';
    }

    let data = {
      form_id: formId,
      rdSession: rd_session,
      template_id: template_id,
      page: page, //跳转到全部订单页面 
      orderId: orderId
    }

    http.getReq(requestUrl,data, function (res) {//回调
      //--------------------支付成功/失败后的跳转---------------------------------
      setTimeout(function () {
        let url = '';
        if(ret){
          url = '/pages/user/pages/orders/orders'; //跳转到全部
        }else{
          url= '/pages/user/pages/orders/orders?activeIndex=1&statusOri=10'; //跳转到待付款订单列表
        }
        wx.redirectTo({
          url: url
        })
      }, 1500)
      console.log('发送模板消息成功');
    });

  },
  //修改订单状态
  payCallBack: function (orderId, rd_session){
    http.getReq('/weixin/order/payCallBack', {
      'orderId': orderId,
      'rdSession': rd_session
    },function(res){
      console.log('修改订单状态');
      console.log(res);
    });
  },
  //获取最大最小价格
  getNewList: function (itemList) {//获取最大最小价格
    if (itemList.length > 0) {
      for (let p = 0; p < itemList.length; p++) {
        let skus = itemList[p].skus;
        if (skus.length > 0) {
          let skuPrices = [];
          for (let s = 0; s < skus.length; s++) {
            skuPrices.push(skus[s].price);
          }

          itemList[p].minPrice = Math.min(...skuPrices);
          itemList[p].maxPrice = Math.max(...skuPrices);
        }
      }
      this.data.itemList = itemList;
    }
  },
  //一键复制订单号：
  copyOrderId: function (e) {
    console.log(e);
    let orderId = e.currentTarget.dataset.orderid;
    wx.setClipboardData({//设置系统剪贴板的内容
      data: orderId,
      success: function (res) {
        wx.getClipboardData({//系统获取剪切板内容
          success: function (res) {
            console.log(res.data)
          }
        })
      }
    })

  },
})